import axios from "axios";
import {ElMessage} from "element-plus";

// 定义常量
const BASE_URL = 'http://localhost:8080/api/';
const TIMEOUT = 30 * 1000;
const HTTP_STATUS_UNAUTHORIZED = 401;
const ERROR_CODE_UNAUTHORIZED = 40100;
const ERROR_CODE_NO_PERMISSION = 40101;

// 创建 axios 实例
const myAxios = axios.create({
    baseURL: BASE_URL,
    timeout: TIMEOUT,
    withCredentials: true,
});

// 封装响应错误处理函数
const handleResponseError = (error) => {
    if (error.message.includes("timeout")) {
        ElMessage.error("请求超时");
    } else if (error.message.includes("Network Error")) {
        ElMessage.error("服务器异常");
    }
    return Promise.reject(error);
};

// 全局请求拦截器
myAxios.interceptors.request.use(
    function (config) {
        // Do something before request is sent
        return config
    },
    function (error) {
        // Do something with request error
        return Promise.reject(error)
    },
)

// 全局响应拦截器
myAxios.interceptors.response.use(
    function (response) {
        const {data} = response
        // 未登录
        if (data.code === 40100) {
            // 不是获取用户信息的请求，并且用户目前不是已经在用户登录页面，则跳转到登录页面
            if (
                !response.request.responseURL.includes('user/getLoginUser') &&
                !window.location.pathname.includes('/user/login')
            ) {
                ElMessage.warning('请先登录')
                window.location.href = `/user/login?redirect=${window.location.href}`
            }
        }
        return response.data
    },
    function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error)
    },
)

export default myAxios;